﻿using System;
using System.Windows.Forms;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;

namespace MyCompany.StartupToolset
{
  public partial class CalculationControl : UserControl
  {
    public CalculationControl()
    {
      InitializeComponent();
    }

    private void CalculationControl_Load(object sender, EventArgs e)
    {
      OperatorCombo.SelectedIndex = 0;
      FirstArgEdit.Text = "0";
    }

    private void CalculateButton_Click(object sender, EventArgs e)
    {
      try
      {
        int firstArg = Int32.Parse(FirstArgEdit.Text);
        int secondArg = Int32.Parse(SecondArgEdit.Text);
        int result = 0;
        switch (OperatorCombo.Text)
        {
          case "+":
            result = firstArg + secondArg;
            break;
          case "-":
            result = firstArg - secondArg;
            break;
          case "*":
            result = firstArg * secondArg;
            break;
          case "/":
            result = firstArg / secondArg;
            break;
          case "%":
            result = firstArg % secondArg;
            break;
        }
        ResultEdit.Text = result.ToString();
      }
      catch (SystemException)
      {
        ResultEdit.Text = "#Error";
      }
      LogCalculationToOutput(FirstArgEdit.Text, SecondArgEdit.Text, OperatorCombo.Text,
        ResultEdit.Text);
    }

    private void LogCalculation(string firstArg, string secondArg, string operation,
      string result)
    {
      string message = String.Format("Calculation executed: {0} {1} {2} = {3}",
        firstArg, operation, secondArg, result);
      IVsActivityLog log =
          Package.GetGlobalService(typeof(SVsActivityLog)) as IVsActivityLog;
      if (log == null) return;

      log.LogEntry(
        (result == "#Error")
          ?(UInt32) __ACTIVITYLOG_ENTRYTYPE.ALE_ERROR
          : (UInt32)__ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION,
        "Calculation", message);
    }

    private void LogCalculationToOutput(string firstArg, string secondArg, string operation,
      string result)
    {
      string message = String.Format("Calculation executed: {0} {1} {2} = {3}\n",
        firstArg, operation, secondArg, result);

      IVsOutputWindow outWindow =
        Package.GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow;
      IVsOutputWindow2 outWindow2 =
        Package.GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow2;
      Guid generalWindowGuid = VSConstants.GUID_OutWindowGeneralPane;
      IVsOutputWindowPane windowPane;
      outWindow.GetPane(ref generalWindowGuid, out windowPane);
      windowPane.OutputString(message);
    }
  }
}
